<?PHP

class Input
{
    const ESC = 27;
    const SPACE = 32;
    const ENTER = 10;
    const TAB = 9;
    const BS = 127;
    const UP = 265;
    const DOWN = 266;
    const LEFT = 268;
    const RIGHT = 267;

    public $quitKey = Input::ESC;

    public function __construct()
    {
        system("stty -echo -icanon");
    }

    public function get()
    {
        $key = null;

        while ($key == null)
        {
            $s = fread(STDIN, 8);
            $len = strlen($s);
            if ($len == 1)
                $key = ord($s);
            else if ($len == 3 && ord($s[0]) == 27 && ord($s[1]) == 91)
                $key = 200 + ord($s[2]);
        }

        return $key;
    }

    public function run($call, & $data = null, $prompt = "")
    {
        while (1)
        {
            if (is_callable($prompt))
                call_user_func_array($prompt, array(& $data));
            else
                printf($prompt);

            $key = $this->get();
            if ($key == $this->quitKey)
                break;

            call_user_func_array($call, array($key, & $data));
        }
    }

    public function __destruct()
    {
        system("stty echo icanon");
    }
}

/*
 * $input = new Input();
 * $input->run(function($key, & $data){
 *     echo $key;
 * });
 */
